package com.salt.modules.sys.web;

import com.salt.common.json.AjaxJson;
import com.salt.core.oss.OssTemplate;
import com.salt.core.oss.model.SaltFile;
import com.salt.core.persistence.Page;
import com.salt.core.tool.utils.StringUtil;
import com.salt.core.web.BaseController;
import com.salt.modules.sys.entity.BackgroundImageFiles;
import com.salt.modules.sys.service.BackgroundImageFilesService;
import com.salt.modules.sys.utils.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;


/**
 * (BackgroundImageFiles)表控制层
 *
 * @author makejava
 */
@Api(tags = "背景图片")
@RestController
@CrossOrigin
@RequestMapping("/sys/background/image")
public class BackgroundImageFilesController extends BaseController {
    /**
     * 服务对象
     */
    @Resource
    private BackgroundImageFilesService backgroundImageFilesService;
    @Resource
    private OssTemplate ossTemplate;


    /**
     * @Author yan
     * @param backgroundImageFiles 查询内容
     * @param pageNo 页码
     * @param pageSize 每页大小
     * @return
     */
    @ApiOperation(value = "分页查询:根据前台参数分页查询")
    @GetMapping("allLimit")
    public AjaxJson list(BackgroundImageFiles backgroundImageFiles, @RequestParam(required = false) int pageNo, @RequestParam(required = false) int pageSize) {
        if(backgroundImageFiles == null){
            backgroundImageFiles = new BackgroundImageFiles();
        }

        backgroundImageFiles.setUserId(UserUtils.getUser().getId());

        Page<BackgroundImageFiles> page = backgroundImageFilesService.findPage(new Page<BackgroundImageFiles>(pageNo, pageSize), backgroundImageFiles);
        if(page.getList() != null && page.getList().size() > 0){
            for (BackgroundImageFiles files : page.getList()) {
                if(StringUtil.isNotBlank(files.getNewFileName())){
                    files.setNewFileName(ossTemplate.outerFileLink(files.getNewFileName()));
                }
            }
        }
        return AjaxJson.success().put("page", page);
    }



    /**
     * @Author yan
     * @param file
     * @return
     */
    @ApiOperation(value = "上传文件的处理 并保持文件信息保存到数据库")
    @PostMapping("/upload")
    public AjaxJson upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return AjaxJson.success().put("msg", "文件不能为空");
        } else {
            String extension =FilenameUtils.getExtension(file.getOriginalFilename());

            if(extension == null || (extension.toLowerCase().indexOf("jpg") == -1 && extension.toLowerCase().indexOf("jpeg") == -1 &&extension.toLowerCase().indexOf("png") == -1) ){
                return AjaxJson.error("请选择正确的文件格式，jpg，jpeg，png");
            } else {
                extension = "." + extension;
            }

            SaltFile saltFile = ossTemplate.putFile(file);
            //获取文件的后缀       getExtension//获取此文件类型的公用文件扩展名。
            //获取文件大小
            long size = file.getSize();
            //文件类型
            BackgroundImageFiles backgroundImageFiles = new BackgroundImageFiles();
            backgroundImageFiles.setSize(String.valueOf(size));
            backgroundImageFiles.setExt(extension);
            backgroundImageFiles.setOldFileName(saltFile.getOriginalName());
            backgroundImageFiles.setNewFileName(saltFile.getName());
            backgroundImageFiles.setPath(saltFile.getLink());
            backgroundImageFiles.setCreateDate(new Date());
            backgroundImageFiles.setUserId(UserUtils.getUser().getId());
            //将文件存入数据库
            backgroundImageFilesService.saveFile(backgroundImageFiles);
            return AjaxJson.success().put("msg", "上传成功").put("id", backgroundImageFiles.getId());
        }
    }


    /**
     * @Author yan
     * @param id
     * @param request
     * @param response
     * @return
     */
    @ApiOperation(value = "文件下载")
    @GetMapping("/download")
    public AjaxJson download(String id, HttpServletRequest request, HttpServletResponse response){
        //获取文件信息
        BackgroundImageFiles backgroundImageFiles = backgroundImageFilesService.queryById(id);
        if (backgroundImageFiles==null){
            return AjaxJson.success().put("msg", "此文件失效,请重新上传");
        }
        String fileName = backgroundImageFiles.getOldFileName();
        String objectName = backgroundImageFiles.getNewFileName();
        ossTemplate.downloadFile(request, response, fileName, objectName);

        backgroundImageFiles.setDownCounts(backgroundImageFiles.getDownCounts() == null ? 1 : backgroundImageFiles.getDownCounts() + 1);
        backgroundImageFiles.setUpdateDate(new Date());
        backgroundImageFilesService.update(backgroundImageFiles);
        return AjaxJson.success().put("msg", "下载成功");
    }

    /**
     * 根据主键删除数据
     * @Author yan
     * @param id
     * @return
     */
    @ApiOperation(value = "删除文件信息")
    @GetMapping("/delete")
    public AjaxJson delete(String id){
        //根据Id查询信息
        BackgroundImageFiles backgroundImageFiles = backgroundImageFilesService.queryById(id);
        if(backgroundImageFiles.getUserId().equals("0") || !backgroundImageFiles.getUserId().equals(UserUtils.getUser().getId())){
            return AjaxJson.error("无法删除其他人信息");
        }

        ossTemplate.removeFile(backgroundImageFiles.getNewFileName());
        //删除数据库中的记录
        backgroundImageFilesService.deleteById(id);
        return AjaxJson.success().put("msg", "删除成功");
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @ApiOperation(value = "通过主键查询单条数据")
    @GetMapping("selectOne")
    public AjaxJson selectOne(String id) {
        BackgroundImageFiles backgroundImageFiles = this.backgroundImageFilesService.queryById(id);
        return AjaxJson.success().put("fixedFiles", backgroundImageFiles);
    }
}